//
//  ShoppingMallDetails.m
//  ELife
//
//  Created by fenglu on 11-7-6.
//  Copyright 2011年 __MyCompanyName__. All rights reserved.
//

#import "ShoppingMallDetails.h"
#import "GTMBase64.h"
#include "GDataXMLNode.h"
#import "ShoppingCell.h"
#import "LoginController.h"
#import "mailAddress.h"
#import "ShowUserMailAddress.h"
#import "AlertView.h"
#import "showShopCard.h"

@implementation ShoppingMallDetails
@synthesize good_id, dataArray;
- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        // Custom initialization
    }
    app = [ELifeAppDelegate App];
    return self;
}

- (void)dealloc
{
    [pay release];
    [dataArray release];
    [super dealloc];
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    
    flowcover = [[FlowCoverView alloc] initWithFrame:CGRectMake(0, 10, 320, 70)];
    [flowcover setDelegate:self];
//    [self.view addSubview:flowcover];
    UIView* view2 = [[UIView alloc] initWithFrame:CGRectMake(10, 90, 320, 100)];
    [view2 setBackgroundColor:[UIColor whiteColor]];
    [view2 addSubview:flowcover];
    self.tableView.tableHeaderView = view2;

    [self openMyData];
    
    [self.tableView setBackgroundView:app.backImage];
    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;
 
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
}


- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [app controllNum:0 setNavigationBar:NO animated:NO];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
}

- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

#pragma mark - Table view data source

-(CGFloat) tableView:(UITableView*) tableView 
heightForRowAtIndexPath:(NSIndexPath*) indexPath
{
	NSInteger section = [indexPath section];
	if (section == 1) {
		return 160;
	}else {
		return 44;
	}
    
	
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
#warning Potentially incomplete method implementation.
    // Return the number of sections.
    return 5;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
#warning Incomplete method implementation.
    // Return the number of rows in the section.
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
    }
    NSInteger section = [indexPath section];
    
    if (section == 0) {
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        UISegmentedControl* segment = [[UISegmentedControl alloc] initWithItems:[NSArray arrayWithObjects:@"简介", @"详情", @"评论", nil]];
        segment.frame = CGRectMake(30, 7, 260, 30);
        segment.selectedSegmentIndex = 0;
        [cell addSubview:segment];
        [segment release];
    }else if(section == 1)
    {
        ShoppingCell* cell2 =  (ShoppingCell*)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if (cell2 == nil) {
            NSArray *nib = [[NSBundle mainBundle]loadNibNamed:@"ShoppingCell" owner:self options:nil];
            cell2 = [nib objectAtIndex:2];

            
            int l = 5001;
            for (int i = 0; i<6; i++) {
                UILabel* label1 = (UILabel*)[cell2 viewWithTag:l+i];
                if ([dataArray count] > i) {
                    [label1 setText:[dataArray objectAtIndex:i]];
                }
                
            }
            cell2.selectionStyle = UITableViewCellSelectionStyleNone;
            
            return cell2;
        }
    }else if(section == 2)
    {
        ShoppingCell* cell2 =  (ShoppingCell*)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
//        if (cell2 == nil) {
            NSArray *nib = [[NSBundle mainBundle]loadNibNamed:@"ShoppingCell" owner:self options:nil];
            cell2 = [nib objectAtIndex:3];
            
            
            int l = 5001;
            for (int i = 0; i<6; i++) {
                UILabel* label1 = (UILabel*)[cell2 viewWithTag:l+i];
                [label1 setText:[dataArray objectAtIndex:i]];
            }
            cell2.selectionStyle = UITableViewCellSelectionStyleNone;
            
            return cell2;
//        }

        
    }else if(section == 3)
    {
//        [cell.textLabel setText:@"直接支付"];
        ShoppingCell* cell2 =  (ShoppingCell*)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        //        if (cell2 == nil) {
        NSArray *nib = [[NSBundle mainBundle]loadNibNamed:@"ShoppingCell" owner:self options:nil];
        cell2 = [nib objectAtIndex:4];
        
        UIButton* button1 = [cell2 viewWithTag:5001];
        [button1 addTarget:self action:@selector(button1Action) forControlEvents:UIControlEventTouchUpInside];
        UIButton* button2 = [cell2 viewWithTag:5002];
        [button2 addTarget:self action:@selector(button2Action) forControlEvents:UIControlEventTouchUpInside];
        cell2.selectionStyle = UITableViewCellSelectionStyleNone;
        
        return cell2;

    }else if(section == 4)
    {
        [cell.textLabel setText:@"信用卡分期支付"];
    }
    // Configure the cell...
    
    return cell;
}

/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
    }   
    else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
{
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/
#pragma mark 回调
-(void) button1Action
{
    if (pay == nil) {
        pay = [[PayClass alloc] init:self payStyle:SHOPINGMALLPAY];
    }
    [pay setShopId:good_id];
    [pay openShopingMallStyle];
}

-(void) button2Action
{
    [app showProgressDialog:@"请稍候"];
    
    NSURL* url = [NSURL URLWithString:[NSString stringWithFormat:@"%@goods_order.php?", [[NSBundle mainBundle] localizedStringForKey:(@"BussinessHost") value:@"" table:nil]]];
    
    NSMutableDictionary *param = [[NSMutableDictionary alloc]initWithCapacity:4];
    [param setObject:@"add_goodsorder" forKey:@"action"];
    NSString* userid = [GetMyData getUserId];
    [param setObject:userid forKey:@"user_id"];
    [param setObject:good_id forKey:@"goods_id"];
    [param setObject:@"1" forKey:@"goods_number"];
//    [param setObject:[password text] forKey:@"property_id"];
    
    
    [param setObject:[[NSBundle mainBundle] localizedStringForKey:(@"ClientVersion") value:@"" table:nil] forKey:@"version"];
    
    
    NSDictionary* dic = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:url, @"add_goodsorder:", nil] forKeys:[NSArray arrayWithObjects:@"url", @"requestMethod", nil]];
    
    [[app httpRequestPoint]openUrl:dic postParam:param target:self];

}


#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([indexPath section] == 4) {
        [self button1Action];
    }
}




-(void) openMyData
{
    [app showProgressDialog:@"请稍候"];
    NSMutableDictionary *param = [[NSMutableDictionary alloc]initWithCapacity:3];
    [param setObject:@"get_goodsinfo" forKey:@"action"];
    [param setObject:good_id forKey:@"goods_id"];
//    [param setObject:@"111" forKey:@"goods_id"];
    [param setObject:[[NSBundle mainBundle] localizedStringForKey:(@"ClientVersion") value:@"" table:nil] forKey:@"version"];
    NSString* urlRegister = [NSString stringWithFormat:@"%@%@", [[NSBundle mainBundle] localizedStringForKey:(@"BussinessHost") value:@"" table:nil], @"goods.php?"];
    
    NSDictionary* dic = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:[NSURL URLWithString:urlRegister], @"iRequestFinished:", nil] forKeys:[NSArray arrayWithObjects:@"url", @"requestMethod", nil]];
    
    [[app httpRequestPoint]openUrl:dic postParam:param target:self];
    
    [param release];

}


-(void) add_goodsorder:(NSData*) data
{
    [app hideProgressDialog];
    
    NSMutableString* retStr = [[NSMutableString alloc]  initWithData:[GTMBase64 decodeData:data] encoding:NSUTF8StringEncoding];
    NSLog(@"%@", retStr);
    [retStr release];
    
    [AlertView showAlert:@"加入购物车成功"];
}


-(void)iRequestFinished:(NSData*) data
{
    [app hideProgressDialog];
    NSMutableString* retStr = [[NSMutableString alloc]  initWithData:[GTMBase64 decodeData:data] encoding:NSUTF8StringEncoding];
    NSLog(@"%@", retStr);
    [retStr release];
    
    
    
    GDataXMLDocument *doc = [[GDataXMLDocument alloc] initWithData:[GTMBase64 decodeData:data] options:0 error:nil];
    GDataXMLElement* rootElement = [doc rootElement];
    //    NSLog(@"--------root element:--------\n%@",rootElement);
    NSArray* children = [rootElement children];
    //NSLog(@"--------root's children:--------\n%@", children);
    GDataXMLElement* bodyElement = [[rootElement elementsForName:@"body"]objectAtIndex:0];
    //    NSLog(@"--------body:--------\n%@", bodyElement);
    GDataXMLElement* goods = [[bodyElement elementsForName:@"intro"] objectAtIndex:0];
    NSLog(@"--------goods:--------\n%@", goods);
    NSString* goods_name = [[[goods elementsForName:@"goods_name"]objectAtIndex:0] stringValue];
    NSString* market_price = [[[goods elementsForName:@"market_price"]objectAtIndex:0] stringValue];
    NSString* goods_price = [[[goods elementsForName:@"goods_price"]objectAtIndex:0] stringValue];
    NSString* goods_vip = [[[goods elementsForName:@"goods_vip"]objectAtIndex:0] stringValue];
    NSString* daijinquan = [[[goods elementsForName:@"daijinquan"]objectAtIndex:0] stringValue];
    NSString* is_creditpay = [[[goods elementsForName:@"is_creditpay"]objectAtIndex:0] stringValue];
    
    [self setDataArray:[NSArray arrayWithObjects:goods_name, market_price, goods_price, goods_vip, daijinquan, is_creditpay , nil]];
    NSLog(@"%@", dataArray);
    
    [self.tableView reloadData];
}


#pragma mark -
#pragma mark flowCover
- (int)flowCoverNumberImages:(FlowCoverView *)view
{
    return 3;
}


- (UIImage *)flowCover:(FlowCoverView *)view cover:(int)cover
{
    if (cover == 0) {
        return [UIImage imageNamed:@"90x90-10.jpg"];
    }else if (cover == 1) {
        return [UIImage imageNamed:@"90x90-11.jpg"];
    }else if (cover == 2) {
        return [UIImage imageNamed:@"90x90-12.jpg"];
    }
}


- (void)flowCover:(FlowCoverView *)view didSelect:(int)cover
{
    NSLog(@"select=%i", cover);
}


- (void)flowCover:(FlowCoverView *)view dangqian:(int)cover
{
    NSLog(@"dangqian=%i", cover);
}



#pragma mark text
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
	return YES;
}

- (BOOL)textFieldShouldEndEditing:(UITextField *)textField
{
	[textField resignFirstResponder];
	return YES;
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    
    return YES;
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    
	[textField resignFirstResponder];
	return YES;
}

- (BOOL)textViewShouldEndEditing:(UITextView *)textView
{
	[textView resignFirstResponder];
	return YES;
}

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
    return YES;
}


-(void) addOne
{
    
}

#pragma mark 支付回调
-(void) failedNoUserId
{
    LoginController* lc = [[LoginController alloc] init:self];
    [self.navigationController pushViewController:lc animated:YES];
    [lc release];
}


-(void) NotMailAddress
{
    mailAddress* ma = [[mailAddress alloc] initWithStyle:UITableViewStyleGrouped];
    [self.navigationController pushViewController:ma animated:YES];
    [ma release];
}

-(void) getMailFinish:(NSArray*)temp
{
    ShowUserMailAddress* userAddress = [[ShowUserMailAddress alloc] initWithStyle:UITableViewStyleGrouped setDele:pay];
    [userAddress setMyDic:temp];
    [self.navigationController pushViewController:userAddress animated:YES];
    [userAddress release];
}



-(void) registerOver:(NSString*) username
{

}


@end
